<template>
  <dv-full-screen-container>
    <div class="bg content" style="height:100vh;display:flex;flex-direction:column;">
      <!-- 第一行：头部 -->
      <div style="height:42vh;">
        <el-row :gutter="5" style="height:100%;">
          <el-col :span="5" style="height:100%;"><Card1 /></el-col>
          <el-col :span="14" style="height:100%;"><Main /></el-col>
          <el-col :span="5" style="height:100%;"><Card2 /></el-col>
        </el-row>
      </div>
      <!-- 第二行：Dormitory -->
      <div style="height:28vh;">
        <el-row :gutter="10" style="height:100%;">
          <el-col :span="24" style="height:100%;">
            <div style="width: 100%;height:100%;"><Dormitory /></div>
          </el-col>
        </el-row>
      </div>
      <!-- 第三行：Ranking -->
      <div style="height:30vh;">
        <Ranking />
      </div>
    </div>
  </dv-full-screen-container>
</template>

<script setup>
import { reactive, provide, onMounted, onBeforeUnmount } from 'vue'
import Main from "./vue/Head.vue"
import Card1 from "./vue/card1.vue"
import Card2 from "./vue/card2.vue"
import Dormitory from "./vue/Dormitory.vue"
import Ranking from './vue/Ranking.vue'

// 统一数据结构
const state = reactive({
  card1: {
    name: '',
    dorm: '',
    major: '',
    photo: ''
  },
  card2: {
    name: '',
    dorm: '',
    major: '',
    photo: ''
  },
  number: {
    out: 0,
    in: 0,
    notBack: 0,
    notOut: 0
  },
  pie: {
    bed: [0, 0],
    inout: [0, 0, 0, 0]
  },
  table: [],
  excellent: [],
  bad: [],
  ranking: [],
  notice: ''
})

let ws = null

function connectWS() {
  ws = new WebSocket('ws://localhost:8080') // 这里请替换为你的ws地址
  ws.onopen = () => {
    console.log('WebSocket连接已建立')
  }
  ws.onmessage = (event) => {
    // 假设后端推送的数据结构为 { type, data }
    const msg = JSON.parse(event.data)
    switch (msg.type) {
      case 'card1':
        Object.assign(state.card1, msg.data)
        break
      case 'card2':
        Object.assign(state.card2, msg.data)
        break
      case 'number':
        Object.assign(state.number, msg.data)
        break
      case 'pie':
        Object.assign(state.pie, msg.data)
        break
      case 'table':
        state.table = msg.data
        break
      case 'excellent':
        state.excellent = msg.data
        break
      case 'bad':
        state.bad = msg.data
        break
      case 'ranking':
        state.ranking = msg.data
        break
      case 'notice':
        state.notice = msg.data
        break
    }
  }
  ws.onclose = () => {
    console.log('WebSocket已断开，尝试重连...')
    setTimeout(connectWS, 2000)
  }
  ws.onerror = () => {
    ws.close()
  }
}

onMounted(() => {
  connectWS()
})
onBeforeUnmount(() => {
  ws && ws.close()
})

provide('wsState', state)
</script>
<style lang="scss">
.bg {
  background: url(./assets/bg.png) no-repeat center center;
  background-size: cover;
  background-attachment: fixed;
}

.content {
  color: #d3d3d3;
}
</style>